package org.zjvis.datascience.common.vo.dataset;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import lombok.Data;
import org.springframework.util.CollectionUtils;
import org.zjvis.datascience.common.vo.PageVO;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 数据查询渲染相关VO (根据数据集id获取数据集)
 * @date 2021-12-22
 */
@Data
public class DatasetQueryVO extends PageVO {
    private Long id;

    private String table;

    private String name;

    private List<QueryColumn> columns;

    private Integer totalRows;

//    public String toSQLSuffix() {
//        StringBuffer stringBuffer = new StringBuffer();
//        if (!CollectionUtils.isEmpty(columns)) {
//            List<String> parts = columns.stream().map(QueryColumn::toString).collect(Collectors.toList());
//            String orderBy = "order by " + Joiner.on(",").join(parts);
//            stringBuffer.append(" ").append(orderBy);
//        }
//        int offset = (this.getCurPage() - 1) * this.getPageSize();
//        stringBuffer.append(" ");
//        stringBuffer.append(String.format(DatabaseConstant.GP_LIMIT_OFFSET_SQL, this.getPageSize(), offset));
//        return stringBuffer.toString();
//    }

    public String toSortSuffix() {
        StringBuffer stringBuffer = new StringBuffer();
        if (!CollectionUtils.isEmpty(columns)) {
            List<String> parts = columns.stream().map(QueryColumn::toString).collect(Collectors.toList());
            String orderBy = "order by " + Joiner.on(",").join(parts);
            stringBuffer.append(" ").append(orderBy);
        }
        return stringBuffer.toString();
    }

    public static DatasetQueryVO parse(JSONObject configJson) {
        DatasetQueryVO datasetQueryVO = new DatasetQueryVO();
        datasetQueryVO.setCurPage((Integer) configJson.getOrDefault("curPage", 1));
        datasetQueryVO.setPageSize((Integer) configJson.getOrDefault("pageSize", 20));
        datasetQueryVO.setName(configJson.getString("name"));
        if (configJson.containsKey("sortCol")) { //TODO 前端集成后去掉
            datasetQueryVO.setColumns(configJson.getJSONArray("sortCol").toJavaList(QueryColumn.class));
        }
        return datasetQueryVO;
    }


}

@Data
class QueryColumn {

    String name;

    String sort; //ASC|DESC

    public String toString() {
        return name + " " + sort;
    }
}


